import React, { useEffect, useState } from 'react';
import { NavLink } from 'react-router-dom';
import event from '../../events';
import './index.less';
import shenli from '../../assets/imgs/shenli.jpg';
import logo from '../../assets/imgs/logo.png';
import { login, signup } from '../../api/request/user';
import { useAppDispatch } from '../../redux/hook';
import { addtoken } from '../../redux/features/login';
import { validatePassword, validateUsername } from '../../utils';

export default function Login() {
    const [showHide, setShowHide] = useState(true); // 控制登陆、注册显示隐藏
    const loginTextInput = React.createRef<HTMLInputElement>();
    const loginPasswordInput = React.createRef<HTMLInputElement>();
    const registerTextInput = React.createRef<HTMLInputElement>();
    const registerPasswordInput = React.createRef<HTMLInputElement>();
    const registerPasswordInput2 = React.createRef<HTMLInputElement>();
    const dispatch = useAppDispatch();

    useEffect(() => {
        event.emit('login', true);
        return () => {
            event.emit('login', false);
        };
    });

    const registerClick = () => {
        setShowHide(true);
    };
    const LoginClick = () => {
        setShowHide(false);
    };

    function handleLogin() {
        // 暂时未做任何验证
        const username = loginTextInput.current?.value;
        const password = loginPasswordInput.current?.value;
        if (!username || !password) {
            // UI提示
            alert('用户名或密码不能为空');
            return;
        }
        if (!validateUsername(username) || !validatePassword(password)) {
            // UI提示
            alert('用户名或密码格式不正确');
            return;
        }
        login(username, password)
            .then((response) => {
                const data = response.data;
                // 登录成功
                if (data.result.code === 0) {
                    if (!data.data) return;
                    const token = data.data.userToken;
                    localStorage.setItem('token', token);
                    dispatch(addtoken(token));
                    window.location.href = '/';
                } else {
                    alert('登录失败：' + data.result.msg);
                }
            })
            .catch((error) => {
                console.log(error);
            });
    }

    function handleSignup() {
        // 暂时未做任何验证
        const username = registerTextInput.current?.value;
        const password = registerPasswordInput.current?.value;
        const password2 = registerPasswordInput2.current?.value;
        if (!username || !password || !password2) return;
        if (password !== password2) {
            // UI提示
            alert('两次密码不一致');
            return;
        }
        if (!validateUsername(username) || !validatePassword(password)) {
            // UI提示
            alert('用户名或密码格式不正确');
            return;
        }
        signup(username, password)
            .then((response) => {
                const data = response.data;
                // 如果注册成功，保存token
                if (data.result.code === 0) {
                    if (!data.data) return;
                    const token = data.data.userToken;
                    localStorage.setItem('token', token);
                    dispatch(addtoken(token));
                    window.location.href = '/';
                } else {
                    alert('注册失败：' + data.result.msg);
                }
            })
            .catch((error) => {
                console.log(error);
            });
    }

    return (
        <main className="login">
            <div className="box">
                <div className="container">
                    <div className="session_body">
                        <div className="session_left">
                            <div className="session_left_container">
                                <div className="session_left_header">
                                    <img src={logo} alt="" />
                                    <h1>
                                        <NavLink to="/home/attention">评教系统</NavLink>
                                    </h1>
                                </div>
                                <div className="session_left_content">
                                    <h2>基于零知识证明的改良学生匿名评教系统</h2>
                                    <ul>
                                        <li>
                                            使用零知识证明进行身份验证，在验证用户是学校学生的同时无法获知学生的个人信息
                                        </li>
                                        <li>
                                            评教系统不限制学生的评教格式，即不给出固定的评价问卷模板，学生只需要给出星级以及选填的文本评论
                                        </li>
                                        <li>课程评分、评论全部公开</li>
                                    </ul>
                                </div>
                                <div className="session_left_footer">
                                    关于我们：
                                    <a href="https://gitee.com/comedymaker/software-engineering">软件工程项目</a>
                                </div>
                            </div>
                        </div>
                        <div className="session_right">
                            <div className="static">
                                <span className={showHide ? 'active' : ''} onClick={registerClick}>
                                    登录
                                </span>
                                <span className={showHide ? '' : 'active'} onClick={LoginClick}>
                                    注册
                                </span>
                            </div>
                            <form className={showHide ? '' : 'hide'} onSubmit={() => false}>
                                <input ref={loginTextInput} type="text" placeholder="请输入账号"></input>
                                <input ref={loginPasswordInput} type="password" placeholder="请输入密码"></input>
                                <button onClick={handleLogin}>登录</button>
                            </form>
                            <form className={showHide ? 'hide' : ''} onSubmit={() => false}>
                                <input ref={registerTextInput} type="text" placeholder="请输入用户名"></input>
                                <input ref={registerPasswordInput} type="password" placeholder="请输入密码"></input>
                                <input ref={registerPasswordInput2} type="password" placeholder="请确认密码"></input>
                                <button onClick={handleSignup}>注册</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            {/* <div className="left">
                <img src={shenli} alt="" />
            </div>
            <div className="right">
                <div className="logo">
                    <img src={logo} alt="" />
                    <h1>
                        <NavLink to="/home/attention">评教系统</NavLink>
                    </h1>
                </div>
                <div className="box">
                    
                    <div className="static">
                        <span className={showHide ? 'active' : ''} onClick={registerClick}>
                            登录
                        </span>
                        <span className={showHide ? '' : 'active'} onClick={LoginClick}>
                            注册
                        </span>
                    </div>
                    <form className={showHide ? '' : 'hide'} onSubmit={() => false}>
                        <input ref={loginTextInput} type="text" placeholder="请输入账号"></input>
                        <input ref={loginPasswordInput} type="password" placeholder="请输入密码"></input>
                        <button onClick={handleLogin}>登录</button>
                    </form>
                    <form className={showHide ? 'hide' : ''} onSubmit={() => false}>
                        <input ref={registerTextInput} type="text" placeholder="请输入用户名"></input>
                        <input ref={registerPasswordInput} type="password" placeholder="请输入密码"></input>
                        <input ref={registerPasswordInput2} type="password" placeholder="请确认密码"></input>
                        <button onClick={handleSignup}>注册</button>
                    </form>
                </div>
            </div> */}
        </main>
    );
}
